package com.ds.client.screen;

import java.rmi.RemoteException;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.ds.client.support.ServerStub;
import com.ds.support.GameStatus;


/**
 * waiting screen, shows waiting informations
 */
public class WaitingScreen implements Screen{

	Music background;
	InitGame game;
	private Stage waitingStage;
	Image waitingScreen;
	ServerStub serverStub;
	
	
	public WaitingScreen(InitGame initGame){
		game = initGame;
	}
	
	@Override
	public void dispose() {
		waitingStage.clear();
		
	}

	@Override
	public void hide() {
		
	}

	@Override
	public void pause() {
		
	}

	@Override
	public void render(float arg0) {
		Gdx.gl.glClearColor(255, 255, 255, 255);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		try {
			//check if the game is start
			ready();
		} catch (RemoteException e) {
			dispose();
			game.setScreen(game.loseConnScreen);
		}
		waitingStage.draw();
		
	}

	@Override
	public void resize(int arg0, int arg1) {
		
	}

	@Override
	public void resume() {
		
	}

	@Override
	public void show() {
		waitingStage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics
				.getHeight(), false);
		initWaiting();
		try {
			serverStub = new ServerStub();
		} catch (Exception e) {
			dispose();
			game.setScreen(game.loseConnScreen);
		}
	}
	
	public void initWaiting() {
		waitingScreen = new Image(new TextureAtlas(
				"res/waitingScreen/waiting.pack").findRegion("waiting 1"));
		setImagePosition(waitingScreen, 0, 0);
		waitingStage.addActor(waitingScreen);
		Gdx.input.setInputProcessor(waitingStage);
		
		background = Gdx.audio.newMusic(Gdx.files.internal("res/music/background.mp3"));
		background.play();
	}
	
	public void setImagePosition(Image image, float x, float y) {
		image.x = x;
		image.y = y;
	}
	
	/**
	 * check the game is start
	 * @throws RemoteException
	 */
	public void ready() throws RemoteException {
		if (GameStatus.valueOf("RUNING").equals(serverStub.getGameStatus(game.myID))) {
			background.stop();
			dispose();
			game.setScreen(game.getRaceScreen());
		}
	}

}
